<?php
/**
 * Joomla! 1.5 component JoomGPSTracks
 *
 * @version $Id: tracks.php 2009-06-24 15:40:19 svn $
 * @author Michael Pfister
 * @package joomGPStracks
 * @subpackage backend
 * @license GNU/GPL
 * @filesource
 *
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');
/**
 * Model Class Tracks
 */
class JoomgpstracksModelTracks extends JModel {

	/**
	 * Category data array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Category total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

    /**
     *
     * @global array $mainframe
     * @global string $option
     */
    function __construct() {
		parent::__construct();
		global $mainframe, $option;

		// Get the pagination request variables
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart	= $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );

		// In case limit has been changed, adjust limitstart accordingly
//		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
        $limitstart = JRequest::getVar('limitstart',0);

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

		$array = JRequest::getVar('cid', array(0), '', 'array');
		$edit	= JRequest::getVar('edit',true);
		if($edit)
			$this->setId((int)$array[0]);
    }

    /**
     *
     * @return array
     */
	function getData()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_data;
	}
    /**
     *
     * @return array $pagination
     */
 	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

    /**
     *
     * @return string
     */
    function getTotal()  {

		// Lets load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
    }

    /**
     *
     * @global array $mainframe
     * @return string
     */
    function _buildQuery()  {
        global $mainframe;

	$orderby	= $this->_buildContentOrderBy();
        $where      = $this->_buildContentWhere();

        $db =& JFactory::getDBO();

        $query = "SELECT a.*, b.title AS cat FROM"
                . "\n #__gps_tracks AS a"
                . "\n LEFT JOIN #__gps_cats AS b"
                . "\n ON a.catid=b.id"
                . $where
                . $orderby
                ;

        return $query;
    }

    /**
     *
     * @global object $mainframe
     * @global string $option
     * @return string
     */
 	function _buildContentOrderBy()
	{
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest( $option.'filter_order',		'filter_order',		'ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'filter_order_Dir',	'filter_order_Dir',	'',				'word' );

		if ($filter_order == 'ordering'){
			$orderby 	= ' ORDER BY ordering '.$filter_order_Dir;
		} else {
			$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.' , id ';
		}

		return $orderby;
	}

    /**
     *
     * @global object $mainframe
     * @global string $option
     * @return string
     */
    function _buildContentWhere()  {

        global $mainframe, $option;

        $search =& JRequest::getVar('search');
        $where = array();
        $db =& JFactory::getDBO();

        if($search)  {
            $where[] = 'LOWER(a.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
            $where[] = 'LOWER(b.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
            $where[] = 'LOWER(a.date) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
        }
        $where 		= ( count( $where ) ? ' WHERE ' . implode( ' OR ', $where ) : '' );
        
        return $where;
    }

    /**
     *
     * @global object $mainframe
     * @param string $id
     * @return object
     */
    function getTrack($id)  {
        global $mainframe;

        $db =& JFactory::getDBO();

        $query = "SELECT * FROM #__gps_tracks"
                . "\n WHERE id='" . $id . "'";

        $db->setQuery($query);
        $result = $db->loadObject();

        if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}

        return $result;
    }

    /**
     *
     * @param string $id
     */
	function setId($id)
	{
		// Set weblink id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}


    /**
     *
     * @param array $cid
     * @param string $publish
     * @return bool
     */
	function publish($cid = array(), $publish = 1)
	{
		$user 	=& JFactory::getUser();

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );

			$query = 'UPDATE #__gps_tracks'
				. ' SET published = '.(int) $publish
				. ' WHERE id IN ( '.$cids.' )'
				. ' AND ( checked_out = 0 OR ( checked_out = '.(int) $user->get('id').' ) )'
			;
			$this->_db->setQuery( $query );
			if (!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

    /**
     *
     * @param array $cid
     * @return boolean
     */
	function delete($cid = array())
	{
        jimport('joomla.filesystem.file');

		$result = false;

		if (count( $cid ))
		{
			JArrayHelper::toInteger($cid);
			$cids = implode( ',', $cid );
            // delete the images
            $query = "SELECT * FROM #__gps_tracks"
                    . "\n WHERE id IN ( '.$cids.' )";

            $this->_db->setQuery($query);
            $rows = $this->_db->loadObjectList();

            if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}

            foreach($rows as $row)  {
                JFile::delete(JPATH_SITE.DS."images".DS."joomgpstracks".DS."cats".DS.$row->image);
            }

            //delete from DB
			$query = 'DELETE FROM #__gps_tracks'
				. ' WHERE id IN ( '.$cids.' )';
			$this->_db->setQuery( $query );
			if(!$this->_db->query()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
		}

		return true;
	}

        /**
         *
         * @global object $mainframe
         * @return array
         */
        function getCats()  {
            global $mainframe;

            $db =& JFactory::getDBO();

            $query = "SELECT * FROM #__gps_cats";

            $db->setQuery($query);
            $rows = $db->loadObjectList();

            return $rows;
        }

        /**
         *
         * @global object $mainframe
         * @return array
         */
        function getTerrain()  {
            global $mainframe;

            $db =& JFactory::getDBO();

            $query = "SELECT * FROM #__gps_terrain ORDER BY title ASC";

            $db->setQuery($query);
            $rows = $db->loadObjectList();

            return $rows;
        }

    function saveTrack()  {
        global $mainframe;

        jimport('joomla.filesystem.file');
        require_once('../components/com_joomgpstracks/helpers/gpsClass.php');

        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();

        // get the post data
        $catid =& JRequest::getInt('catid');
        $level =& JRequest::getInt('level');
        $title =& JRequest::getVar('title');
        $terrain =& JRequest::getVar('terrain');
        if(count($terrain > 0)):
            $terrain = implode(',', $terrain);
        endif;
        $desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $file =& JRequest::getVar('file', null, 'files', 'array');
        $uid = $user->get('id');
        $date = date("Y-m-d");
        $images =& JRequest::getVar('images', null, 'files', 'array');
        $access =& JRequest::getInt('access');



            // upload the file
            $upload_dir = JPATH_SITE.DS."components".DS."com_joomgpstracks".DS."uploads".DS;
            $filename = JFile::makeSafe($file['name']);
            $filename = str_replace(' ', '_', $filename);
            if (!JFile::upload($file['tmp_name'], $upload_dir.strtolower($filename))) {
                echo "Upload failed!";
            } else {
                chmod($upload_dir.strtolower($filename), 0777);
            }

            // get the start coordinates
            $gps = new gpsClass();
            $gps->gpsFile = "../components/com_joomgpstracks/uploads/".strtolower($filename);
            if($gps->getStartCoordinates())  {
                $start = $gps->getStartCoordinates();
            } else {
                echo "<script type='text/javascript'>alert('".JText::_('GPS_NO_SUPPORT')."');window.history.back(-1);</script>";
                exit;
            }

            $file = '../components/com_joomgpstracks/uploads/'.strtolower($filename);
            $start_n = $start[1];
            $start_e = $start[0];
            $coords = $gps->getCoords($file);
            $distance = $gps->getDistance($coords);
            if($distance == NULL)  {
                echo "<script type='text/javascript'>alert('".$distance."');window.history.back(-1);</script>";
                exit;
            }

            // call the elevation function
            $ele = $gps->getElevation($coords);


            // images upload part
            $cfg = joomgpstracksHelper::getConfig();
            $types = explode(',',$cfg->type);
            if(count($images) > 0 )  {
                JFolder::create(JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title),0777);
                $img_dir = JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title);
                foreach($images['name'] as $key => $value)  {
                    $ext = explode('.',$images['name'][$key]);
                    if(in_array($ext[1], $types)) {
                        $path = $img_dir.DS.strtolower($images['name'][$key]);
                        $this->createImage($images['tmp_name'][$key], $ext[1], $path);
                    }
                }
            }



            $query = "INSERT INTO #__gps_tracks SET"
                    . "\n uid='".$uid."',"
                    . "\n catid='".$catid."',"
                    . "\n title='".$title."',"
                    . "\n file='".strtolower($filename)."',"
                    . "\n terrain='".$terrain."',"
                    . "\n description='".$desc."',"
                    . "\n date='".$date."',"
                    . "\n start_n='".$start_n."',"
                    . "\n start_e='".$start_e."',"
                    . "\n distance='".$distance."',"
                    . "\n ele_asc='".$ele[0]."',"
                    . "\n ele_desc='".$ele[1]."',"
                    . "\n level='".$level."',"
                    . "\n access='".$access."'"
                    ;

            $db->setQuery($query);
            $db->query();

            if ($db->getErrorNum()) {
                echo $db->stderr();
                    return false;
                } else {
                    return true;
                }

    }

        /**
         * creates the images
         *
         * @param string $file_tmp_name
         * @param string $ext
         * @param string $filepath
         */
        function createImage($file_tmp_name, $ext, $filepath)  {

               switch ($ext)
               {
                  case 'jpeg':
                  case 'pjpeg':
                  case 'JPG':
                  case 'jpg':
                     $src = ImageCreateFromJpeg($file_tmp_name);
                     break;

                  case 'png':
                     $src = ImageCreateFromPng($file_tmp_name);
                     break;

                  case 'gif':
                     $src = ImageCreateFromGif($file_tmp_name);
                     break;

               }

                list($width,$height)=getimagesize($file_tmp_name);
                $newwidth=460;//set file width to 460
                $newheight=($height/$width)*460;//the height are set according to ratio
                $tmp=imagecreatetruecolor($newwidth,$newheight);
                imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);//resample the image

                switch ($ext)
               {
                case 'jpeg':
                   case 'JPG':
                case 'jpg':
                  $statusupload = imagejpeg($tmp,$filepath,100);//upload the image
                  break;

                case 'png':
                  $statusupload =  imagepng($tmp,$filepath,100);//upload the image
                  break;

                 case 'gif':
                  $statusupload = imagegif($tmp,$filepath,100);//upload the image
                  break;

               }
        }

    function updateTrack()  {
        global $mainframe;

        jimport('joomla.filesystem.file');
        require_once('../components/com_joomgpstracks/helpers/gpsClass.php');

        $db =& JFactory::getDBO();
        $user =& JFactory::getUser();

        // get the post data
        $id =& JRequest::getInt('id');
        $catid =& JRequest::getInt('catid');
        $level =& JRequest::getInt('level');
        $title =& JRequest::getVar('title');
        $terrain =& JRequest::getVar('terrain');
        if(count($terrain > 0)):
            $terrain = implode(',', $terrain);
        endif;
        $desc =& JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW);
        $uid = $user->get('id');
        $date = date("Y-m-d");
        $images =& JRequest::getVar('images', null, 'files', 'array');
        $access =& JRequest::getInt('access');


            // images upload part
            $cfg = joomgpstracksHelper::getConfig();
            $types = explode(',',$cfg->type);
            if(count($images) > 0 )  {
                JFolder::create(JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title),0777);
                $img_dir = JPATH_SITE.DS.'images'.DS.'joomgpstracks'.DS.md5($title);
                foreach($images['name'] as $key => $value)  {
                    $ext = explode('.',$images['name'][$key]);
                    if(in_array($ext[1], $types)) {
                        $path = $img_dir.DS.strtolower($images['name'][$key]);
                        $this->createImage($images['tmp_name'][$key], $ext[1], $path);
                    }
                }
            }



            $query = "UPDATE #__gps_tracks SET"
                    . "\n uid='".$uid."',"
                    . "\n catid='".$catid."',"
                    . "\n title='".$title."',"
                    . "\n terrain='".$terrain."',"
                    . "\n description='".$desc."',"
                    . "\n level='".$level."',"
                    . "\n access='".$access."'"
                    . "\n WHERE id='".$id."'"
                    ;

            $db->setQuery($query);
            $db->query();

            if ($db->getErrorNum()) {
                echo $db->stderr();
                    return false;
                } else {
                    return true;
                }
    }

    /**
     *
     * @param array $rows
     * @return string
     */
    function createCatlist($rows)  {
        $children = array();
	foreach ($rows as $v ) {
		$pt 	= $v->parent;
		$list 	= @$children[$pt] ? $children[$pt] : array();
		array_push( $list, $v );
		$children[$pt] = $list;
	}
        $levellimit = 50;
        $list = JHTML::_('menu.treerecurse', 0, '', array(), $children, max( 0, $levellimit-1 ) );
        $list = array_slice($list, $this->getState('limitstart'), $this->getState('limit'));

        return $list;
    }
}
?>
